<?php
function verifyToken($token)
{
    global $redis_pz;
    $redis = new Redis();
    $redis->connect($redis_pz['host'], $redis_pz['port']);
    $redis->auth($redis_pz['password']);
    $data = $redis->get($token);
    if ($data) {
        $data = json_decode($data, true);
        if ($data['timestamp'] > time()) {
            return true;
        }
    }
    return false;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/functions.php');
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
$data_y = file_get_contents("php://input");
$data_x = json_decode($data_y, true);
$token  = $data_x['token'];
function jxcompa_write($filepath, $parsedCommands)
{
    if (!is_writable($filepath)) {
        echo json_encode(['success' => false, 'message' => 'error: file is not writable']);
        exit;
    }
    $content = '';
    foreach ($parsedCommands as $key => $value) {
        $content .= $key . '->' . $value . ";\n";
    }
    if (file_put_contents($filepath, rtrim($content,'\n')) === false) {
        echo json_encode(['success' => false, 'message' => 'error: file write failed']);
        exit;
    }
    echo json_encode(['success' => true]);
}
function splitcounitotwo($text)
{
    $lines = explode("\n", $text);
    $result = [];
    foreach ($lines as $line) {
        $parts = explode("||", $line);
        $result[] = $parts;
    }
    $resultString = json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    return $resultString;
}
if ($token != '') {
    $token  = encrypt($token, 'D', 'yhsdylpo9342');
} else {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
if (!verifyToken($token)) {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
$userid = $data_x['userid'];
$alists = $data_x['alists'];
$alists = json_decode($alists, true);
$filepath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $userid . '/drivenormalpz.afikconfig';
$kglist = array(
    'head' => $alists[0],
    'title' => $alists[1],
    'password' => $alists[2],
    'bkg1' => $alists[3],
    'bkg2' => $alists[4],
    'notice' => splitcounitotwo($alists[5])
);
jxcompa_write($filepath, $kglist);
